/*
 * @Author: your name
 * @Date: 2019-11-01 10:17:50
 * @LastEditTime: 2019-11-08 16:00:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \koa-example\src\controllers\public.js
 */

const cheerio = require('cheerio');
const superagent = require('superagent');
const charset = require('superagent-charset');
const phantom = require('phantom');
const fs = require('fs');
charset(superagent);

// 抓取百度新闻列表
async function publicImageListController(keyword) {
    
    function delay(second) {
        return new Promise((resolve) => {
            setTimeout(resolve, second * 1000);
        });
    }

    let url = `http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=${keyword}`; //百度图片地址
    function save(url) {
        let ext = url.split('.').pop()
        request(url).pipe(fs.createWriteStream(`..public/image/${new Date().getTime()}.${ext}`));
    }
    (async function() {
        let instance = await phantom.create();
        let page = await instance.createPage();
        let status = await page.open(url);
        let size = await page.property('viewportSize', {
            width: 1920,
            height: 1080
        })
        let $;
        async function pageScroll(i) {
            await delay(1)
            await page.property('scrollPosition', {
                left: 0,
                top: 1000 * i
            })
            let content = await page.property('content')
            $ = cheerio.load(content)
            if($('.imgbox').length < 200) {
                await pageScroll(++i)
            }
        }
        await pageScroll(0)
        let urlList = []
        $('.imgbox').each(function() {
            urlList.push('https://image.baidu.com'+$(this).find('a').attr('href'))
        })
        async function imgSave(i) {
            let status = await page.open(urlList[i])
            await delay(1)
            let content = await page.property('content')
            $ = cheerio.load(content)
            let src = $('#currentImg').attr('src')
            save(src)
            if(i<urlList.length) {
                await imgSave(++i)
            }
        }
        await imgSave(0)
        await instance.exit()
    }());

}

module.exports = {
    publicImageListController
}

